//
//  Oauth2ViewController.m
//  新浪微博
//
//  Created by hbl on 16/2/21.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "Oauth2ViewController.h"
#import "AFNetworking.h"
#import "Access.h"
#import "BLTabBarViewController.h"
@interface Oauth2ViewController ()<UIWebViewDelegate>

@end

@implementation Oauth2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIWebView *loginWeb = [[UIWebView alloc]init];
    loginWeb.frame = self.view.bounds;
    [self.view addSubview:loginWeb];
    loginWeb.delegate = self;
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=701736565&redirect_uri=http://www.hao123.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [loginWeb loadRequest:request];
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *requestString = request.URL.absoluteString;
    NSRange range = [requestString rangeOfString:@"code"];
   
    NSLog(@"%@",requestString);
    if (range.length > 0) {
        requestString = [requestString substringFromIndex:range.location + 5];
        [self getTheAccessToken:requestString];
        return NO;
}
    return  YES;
}


/**
 *  "access_token":"2.00ofcFCG0hj6Uld38f76c54bPOTtZC","remind_in":"157679999","expires_in":157679999,"uid":"5527689968"
 *
 *  @param code <#code description#>
 */
- (void)getTheAccessToken:(NSString *)code
{
    NSString *postUrlString = @"https://api.weibo.com/oauth2/access_token";
    NSURL *postUrl = [NSURL URLWithString:postUrlString];
    NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc]initWithURL:postUrl];
    postRequest.HTTPMethod = @"POST";
    NSString *paramer = [NSString stringWithFormat:@"client_id=701736565&client_secret=2a9f91d007b21f3262d30b324147c647&grant_type=authorization_code&code=%@&redirect_uri=http://www.hao123.com",code];
    postRequest.HTTPBody = [paramer dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:postRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil ];
        Access *access = [Access accessWithDict:resultDict];
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [doc stringByAppendingPathComponent:@"access.data"];
        [NSKeyedArchiver archiveRootObject:access toFile:filePath];
        self.view.window.rootViewController = [[BLTabBarViewController alloc]init];
    }];
    [task resume];

}
@end
